package com.example.freemaker_demo.tools;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public class FreemakerTool {

    private static final Configuration cfg;

    static {
        cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setClassForTemplateLoading(FreemakerTool.class, "/templates");
        cfg.setDefaultEncoding("UTF-8");
    }

    public static void generateFile(String filePath, String tempName, Map<String, Object> params) {
        // 创建文件夹
        new File(filePath.substring(0, filePath.lastIndexOf("/"))).mkdirs();
        Writer out = null;
        try {
            Template template = cfg.getTemplate(tempName);
            out = new FileWriter(filePath);
            template.process(params, out);

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
